package apis

import (
	"encoding/hex"
	"fmt"
	"net/http"
	"note-go/hash"
	"note-go/session"
	"note-go/models"
	"note-go/pkg/database"
	"strings"

	"github.com/gin-gonic/gin"
)

func AccountLogout(c *gin.Context) { 
	sessionID, _ := c.Cookie("session_id")
	_ = session.DeleteSession(sessionID)
	c.Redirect(http.StatusSeeOther, "/login")
}

func AccountLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || strings.TrimSpace(username) == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"status":  "fail",
			"message": "用户名不能为空",
		})
		c.Abort()
		return
	}
	if password == "" || strings.TrimSpace(password) == "" {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"status":  "fail",
			"message": "密码不能为空",
		})
		c.Abort()
		return
	}
	var enPasswordData = hash.SM3(password)
	var enPassword = hex.EncodeToString(enPasswordData)
	var user models.User
	result := database.DB.Where("username = ?", username).
		Where("password = ?", enPassword).
		First(&user)

	if result.Error != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    400,
			"status":  "fail",
			"message": "登录失败，请确认用户名和密码是否正确",
		})
		c.Abort()
		return
	} 
	sessionID := session.NewSessionID()
	fmt.Println("sessionID:" + sessionID)
	c.SetCookie("session_id", sessionID, 3600*24*7, "/", "127.0.0.1", true, true)
	session.SetSession(sessionID, username)
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"status":  "success",
		"message": "登录成功",
		"data": gin.H{
			"username": "admin",
			"name":     "name",
		},
	})
}
